<template>
  <page-header-wrapper :title="false">
    <div>
      <a-row id="home_wrapper" type="flex">
        <a-col id="left_tree" flex="400px">
          <div>
            <a-tree
              checkable
              :show-line="true"
              :show-icon="false"
              :show-leaf-icon="false"
              :treeData="orgAllTreeData"
              :replaceFields="orgTreereplaceFields"
              @select="onSelectOrgTree"
            >
            </a-tree>
          </div>
        </a-col>
        <div style="width:10px"></div>
        <a-col flex="auto">
          <div id="right-content-white">
            <a-card title="" :bordered="false">
            <div class="table-page-search-wrapper">
              <a-form layout="inline">
                <a-row :gutter="48">
                  <a-col :md="6" :sm="12">
                        <a-form-item label="设备型号">
                          <a-select
                            v-model="orgQueryParam.deviceModelCode"
                            placeholder="请选择"
                            default-value=""
                            :allow-clear="true"
                            style="width: 100"
                          >
                            <a-select-option v-for="item in deviceModelData" :value="item.code" :key="item.id">{{
                              item.name
                            }}</a-select-option>
                          </a-select>
                        </a-form-item>
                      </a-col>
                      <a-col :md="6" :sm="12">
                        <a-form-item label="设备状态">
                          <a-select
                            v-model="orgQueryParam.deviceStatus"
                            placeholder="请选择"
                            default-value=""
                            :allow-clear="true"
                            style="width: 100"
                          >
                            <!-- <a-select-option value="ALL">全部</a-select-option> -->
                            <a-select-option value="NORMAL">运行中</a-select-option>
                            <a-select-option value="ABNORMAL">告警</a-select-option>
                            <a-select-option value="FAULT">故障</a-select-option>
                            <a-select-option value="OFFLINE">离线</a-select-option>
                            <a-select-option value="UNBORN">非正常</a-select-option>
                          </a-select>
                        </a-form-item>
                      </a-col>
                  <a-col :md="6" :sm="12">
                    <a-form-item label="设备编码">
                      <a-input v-model="orgQueryParam.keyword" placeholder="" :allow-clear="true" />
                    </a-form-item>
                  </a-col>

                  <a-col :md="6" :sm="12">
                    <span class="table-page-search-submitButtons">
                      <a-button type="primary" @click="() => initQuery()">查询</a-button>
                      <!-- <a-button style="margin-left: 8px" @click="() => queryOrgParam = {}">重置</a-button> -->
                    </span>
                  </a-col>
                </a-row>
              </a-form>

              <div class="table-operator">
                <!-- <a-button type="primary" icon="plus" @click="() => handleAddOrg()">添加</a-button> -->
                <a-popconfirm
                  title="确认删除所选护栏？"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="() => delOrg(orgSelectedRowKeys.join(','))"
                >
                  <a-button v-if="orgSelectedRowKeys.length > 0" type="danger" icon="delete">批量删除</a-button>
                </a-popconfirm>
              </div>

              <template>
                <a-table
                  size="small"
                  bordered
                  :columns="orgColumns"
                  :row-key="(record) => record.id"
                  :data-source="orgData"
                  :pagination="orgPagination"
                  :loading="loading"
                  @change="handleOrgTableChange"
                  :row-selection="{ selectedRowKeys: orgSelectedRowKeys, onChange: onOrgSelectChange }"
                >
                  <span slot="serial" slot-scope="text, record, index">
                    {{ index + 1 }}
                  </span>
                  <span slot="alarmHandledStatus" slot-scope="text, record">

                    <a-tag color="#f50" v-if="record.normalStatus == '00'"> 未处理 </a-tag>
                    <a-tag color="#008aff" v-else-if="record.normalStatus =='11'"> 已处理 </a-tag>
                    <a-tag color="#aaa" v-else> 无 </a-tag>
                  </span>
                  <span slot="status" slot-scope="text, record">

                    <a-tag :color="getStutas(record).color" > {{getStutas(record).name}} </a-tag>
                  </span>
                  <span slot="orgAction" slot-scope="text, record">
                    <a @click="() => showDrawer(record.id)"><a-icon type="eye" /> 详情 </a>
                    <a-divider type="vertical" />
                    <a-popconfirm
                      title="确认删除该护栏？"
                      ok-text="确认"
                      cancel-text="取消"
                      @confirm="() => delOrg(record.id)"
                    >
                      <a href="#"> <a-icon type="delete" /> 删除</a>
                    </a-popconfirm>
                  </span>
                </a-table>
              </template>
            </div>
            </a-card>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-drawer
      :width="360"
      title="设备详情"
      placement="right"
      :closable="false"
      :visible="drawerVisible"
      :after-visible-change="afterVisibleChange"
      @close="onClose"
    >
      <div class="autoMap-box">
      <autoMap :mapInfo="mapInfo" :pointData="pointData"></autoMap>
      </div>
      <ul class="device-info">
        <li>
          <label>设备编码</label>
          <span>{{_.get(pointData,'0.code')}}</span>
        </li>
        <li>
          <label>护栏名称</label>
          <span>{{_.get(pointData,'0.railName')}}</span>
        </li>
        <li >
          <label>当前状态</label>
          <span class="color-status"><a-tag :color="status.color" > {{status.name}} </a-tag></span>
        </li>
        <li>
          <label>所属项目</label>
          <span>{{_.get(pointData,'0.projectName')}}</span>
        </li>
        <li>
          <label>更新时间</label>
          <span>{{_.get(pointData,'0.dataUpdatedAt')}}</span>
        </li>
        <li>
          <label>安装人员</label>
          <span>{{_.get(pointData,'0.installUserName')}}</span>
        </li>
      </ul>
    </a-drawer>
  </page-header-wrapper>
</template>

<script>
import { TreeSelect } from 'ant-design-vue'
import { treeTransArray } from '@/utils/util'
import _ from 'lodash'
import autoMap from "@/components/Map/autoMap";
const orgColumns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' },
  },
  {
    title: '设备型号',
    dataIndex: 'deviceModelCode',
  },
  {
    title: '设备编码',
    dataIndex: 'code',
  },
  {
    title: '所属单位',
    dataIndex: 'orgName',
  },
  {
    title: '归属项目',
    dataIndex: 'projectName',
  },
  {
    title: '当前位置',
    dataIndex: 'address',
  },
  {
    title: '状态',
    dataIndex: 'status',
    needTotal: true,
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '当前告警',
    dataIndex: 'alarmHandledStatus',
    needTotal: true,
    scopedSlots: { customRender: 'alarmHandledStatus' },
  },
  {
    title: '更新时间',
    dataIndex: 'dataUpdatedAt',
    sorter: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'orgAction' },
  },
]
import tool from '@/utils/tool'
export default {
  name: 'DeviceList',
  components: {
    autoMap,
    [TreeSelect.name]: TreeSelect,
    ATreeSelectNode: TreeSelect.TreeNode,
  },
  computed:{
    status:function (){
      return this.deviceStatus.find(o=>o.value==_.get(this.pointData,'0.deviceStatus'))||this.deviceStatus[0];
    }
  },
  created() {
    this._=_;
  },
  data() {
    return {
      mapInfo:[],
      pointData:[],
      deviceStatus:[
        {value:1,color:'#008aff',name:'正常'},
        {value:2,color:'#ff0000',name:'告警'},
        {value:3,color:'#fae600',name:'故障'},
        {value:4,color:'#f09614',name:'离线'},
      ],
      drawerVisible:false,
      loading: false,
      orgTreeSelect: {},
      orgAllTreeData: [],
      orgAllListData: [],
      orgAllData: [],
      orgTreereplaceFields: {
        title: 'lable',
        key: 'id',
        value: 'id',
      },
      formLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
      },
      orgColumns,
      orgSelectedRowKeys: [],
      orgQueryParam: {},
      orgPagination: {
        pageSize: 10,
        showQuickJumper: true,
        showTotal: (total, range) => `共 ${total} 条`,
      },
      orgData: [],
      deviceModelData: []
    }
  },
  mounted() {
    this.getOrgTree()
    this.getDeviceModel()
    this.queryOrgParam()
  },
  methods: {
    getStutas(item){
      return this.deviceStatus.find(o=>o.value==_.get(item,'deviceStatus'))||this.deviceStatus[0];
    },
    afterVisibleChange(val) {
      console.log('drawerVisible', val);
    },
    showDrawer(id) {
      this.drawerVisible = true;
      this.getDeviceDetail(id)
    },
    async getDeviceDetail(id) {
      let res= await this.$http.get('/sysDevice/findById',{params:{id}})
      this.mapInfo=[{
        path:tool.formatpostion(JSON.parse(_.get(res,'data.railPosition')||`{}`))
      }];
      let postion =_.get(res,'data.position').split(',')
      this.pointData=[
        {..._.get(res,'data'),
          gps_lng:_.get(postion,'0'),
          gps_lat:_.get(postion,'1'),
          className:tool.getClassNamme(_.get(res,'data'))
        }
      ]
      console.log(this.pointData,'===this.pointData')

    },
    onClose() {
      this.drawerVisible = false;
    },
    onSelectOrgTree(selectedKeys, info) {
      let selectOrgId = selectedKeys && selectedKeys.length > 0 ? selectedKeys[0] : ''
      if (!selectOrgId) {
        this.orgTreeSelect = {}
      } else {
        //  判断选择的信息类型
        let item = this.orgAllListData.filter((i) => i.id == selectOrgId)[0]
        if (item.type == 'ORG') {
          this.orgTreeSelect = { porgIds: selectOrgId }
        } else if (item.type == 'PROJECT') {
          this.orgTreeSelect = { projectIds: selectOrgId }
        }
      }
      this.orgPagination.current = 1
      this.queryOrgParam()
    },

    getOrgTree() {
      this.$http.get('/web/common/getFullOrgTree').then((res) => {
        if (res.code == 0) {
          this.orgAllListData = treeTransArray(JSON.parse(JSON.stringify(res.data)))
          this.orgAllTreeData = res.data
        }
      })
    },
    getDeviceModel() {
      this.$http.get('/web/dict/getDeviceModel').then((res) => {
        if (res.code == 0) {
          this.deviceModelData = res.data
        }
      })
    },
    onOrgSelectChange(selectedRowKeys) {
      this.orgSelectedRowKeys = selectedRowKeys
    },
    handleOrgTableChange(pagination, filters, sorter) {
      this.orgPagination.current = pagination.current
      this.orgPagination.pageSize = pagination.pageSize
      this.queryOrgParam(pagination.current, pagination.pageSize)
    },
    delOrg(id) {
      this.loading = true
      let param = { projectIds: id }
      this.$http.delete('/web/rail/delete', { params: param }).then((res) => {
        this.loading = false
        if (res.code == 0) {
          this.$notification['success']({
            message: '成功',
            description: '设备已删除',
          })
          this.orgPagination.current = 1
          this.queryOrgParam()
        } else {
          this.$notification['error']({
            message: '错误',
            description: res.message,
            duration: 4,
          })
        }
      })
    },
    queryOrgParam() {
      this.loading = true
      let param = Object.assign({}, this.orgQueryParam)
      param = Object.assign(param, this.orgTreeSelect)
      param.start = this.orgPagination.current
      param.limit = this.orgPagination.size
      this.$http.get('/web/device/page', { params: param }).then((res) => {
        this.loading = false
        if (res.code == 0) {
          let data = res.data
          this.orgData = data.records
          const pagination = { ...this.pagination }
          // Read total count from server
          // pagination.total = data.totalCount;
          // pagination.totalPage = data.pages
          pagination.total = data.total
          pagination.current = data.current
          pagination.pageSize = data.size
          console.log('pagination',pagination)
          this.orgPagination = pagination
        }
      })
    },
   initQuery(){
     this.orgPagination.current = 1;
     this.queryOrgParam();
   }
  },
}
</script>
<style scoped lang="less">
.autoMap-box{
  height: 240px;
}
.device-info{
  margin: 0;
  padding: 0;
  li{
    display: flex;
    justify-content: space-between;
    margin-top:20px;
    align-items: center;
    label{
      font-size: 14px;
      color: #fff;
      width:180px;

    }
    span{
      text-align: right;
      display: block;
      width: calc(~"100%-220px");
      font-size: 12px;
      color: #999;

    }
    .color-status{
      span{
        color: #fff;
      }
    }
  }
}

</style>